<template>
  <div class="login">
    <van-nav-bar title="登录页面" />
    <van-form @submit="login">
      <van-field
        v-model="mobile"
        name="用户名"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        type="number"
        name="密码"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoding"
          :loading="isLoding"
          loading-text="登陆中..."
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// import axios from '@/utils/request'
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '17375007269',
      code: 246810,
      rules: {
        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            // 手机号正则
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      },
      isLoding: false
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    // 当表单校验通过之后，才能发送请求，所以要给表单注册提交事件
    // 发送登录请求
    async login() {
      this.isLoding = true
      // try-catch  一旦代码有错，会影响到后续代码的执行，就用try-catch
      try {
        /*   const res = await axios({
          method: 'POST',
          url: '/v1_0/authorizations',
          data: {
            mobile: this.mobile,
            code: this.code
          }
        }) */
        // 以上Ajax代码封装到api/user.js中
        const res = await userLogin(this.mobile, this.code)
        console.log(res)
        // 将token存到本地存储和Vuex中
        this.setToken(res.data)
        this.$toast.success('登录成功')
        // 登录成功跳转到首页
        this.$router.push('/')
      } catch {
        this.$toast.fail('失败文案')
      }
      // 无论请求成功还是失败，都要执行
      this.isLoding = false
    }
  }
}
</script>

<style lang="less"></style>
